package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    /**
     * 当前线程共享数据
     */
    private ThreadLocal<OrderSubmitVo> submitVoThreadLocal = new ThreadLocal<>();

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    WmsFeignService wmsFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

//    @Transactional(timeout = 30) //a事务的所有设置就传播到了和他共用一个事务的
//    public void a(){
//        b(); //a事务共用一个事务
//        c(); //新事务（出现问题它不会回滚）
//        OrderServiceImpl orderService = (OrderServiceImpl) AopContext.currentProxy();
//        orderService.b();
//        orderService.c();
//        int i = 10/0;
//    }
//    @Transactional(propagation = Propagation.REQUIRED,timeout = 2)
//    public void b(){
//
//    }
//    @Transactional(propagation = Propagation.REQUIRES_NEW,timeout = 20)
//    public void c(){
//
//    }


    //本地事务，在分布式系统下，只能控制住自己的回滚，控制不了其他服务的回滚
    //分布式事务：最大原因
    //seata全局事务
    //@GlobalTransactional  此AT模式不适合高并发
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        submitVoThreadLocal.set(vo);
        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        //获取当前登录用户
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        //锁库存默认状态码为成功0
        response.setCode(0);
        //1、验证令牌【令牌的对比和删除必须保证原子性，所以使用lua脚本】
        //返回值为0（令牌失败）或1（删除成功）
        String script = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        //原子令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Collections.singletonList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId()), orderToken);
        if (result == 0L) {
            //令牌验证失败
            response.setCode(1);
            return response;
        } else {
            //令牌验证成功
            //下单，去创建订单，验令牌，验价格，锁库存……
            //1、创建订单，订单项等信息
            OrderCreateTo order = createOrder();
            //2、验价,页面提交的和后台计算的金额差值绝对值小于0.01
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //金额对比
                // 3、保存订单到数据库
                saveOrder(order);
                // 4、库存锁定,只要有异常回滚订单数据
                //库存成功了，但是网络原因超时了，订单回滚，库存不滚
                //需要订单号、所有订单项（skuId、skuName、num）
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                //封装要锁定的订单项所有数据(skuId、数量等)
                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);
                //远程调用锁定库存
                //为了保证高并发，库存服务自己回滚，可以发消息给库存服务
                //库存服务也可以使用自动解锁模式
                R r = wmsFeignService.orderLockStock(lockVo);
                if (r.getCode() == 0) {
                    //锁定成功
                    response.setOrder(order.getOrder());
                    //TODO 5、远程扣减积分
                    //int i = 10/0;  //订单回滚，但是库存不滚
                    // 订单创建成功，发送消息给MQ
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                } else {
                    //锁定失败
                    //String msg = (String) r.get("msg");
                    //throw new NoStockException(msg);
                    //TODO 和雷神不一样
                    //throw new NoStockException();
                    response.setCode(3);
                }
                return response;
            } else {
                //金额对比失败，返回码为2
                response.setCode(2);
                return response;
            }
        }
       /* String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId());
        if (orderToken!=null && orderToken.equals(redisToken)){
            //令牌通过,删除缓存的令牌
            redisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId());
        }else {
            //不通过
        }*/
    }


    @Override
    public void closeOrder(OrderEntity entity) {
        //查看当前这个订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        //因为已经过了三十分钟，如果是代付款状态，就关单
        if (OrderStatusEnum.CREATE_NEW.getCode().equals(orderEntity.getStatus())) {
            //将要修改的订单数据封装到新的实体中
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity, orderTo);
            try {
                //立即给MQ发送关完订单的消息
                //TODO 保证消息一定会发送出去，每一个消息都可以做好日志记录（给数据库保存每一个消息的详细信息）
                //TODO 定期扫描数据库将失败的消息在发送一遍
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            } catch (Exception e) {
                //TODO 将没发送成功的消息进行重试发送
            }
        }
    }


    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        //根据订单号查询订单信息
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        //格式化总金额为两位小数
        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(order.getOrderSn());

        //获取第一个订单项名称作为支付时显示的主题
        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity entity = order_sn.get(0);
        payVo.setSubject(entity.getSkuName());
        //设置支付时订单备注
        payVo.setBody(entity.getSkuAttrsVals());
        return payVo;
    }


    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberResponseVo memberRespVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId()).orderByDesc("id")
        );
        //遍历拿到所有订单项
        List<OrderEntity> orderSn = page.getRecords().stream().peek(order -> {
            //查询所有订单详情信息封装进orderEntity
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
        }).collect(Collectors.toList());
        //设置用户订单列表页详情的订单项信息
        page.setRecords(orderSn);
        return new PageUtils(page);
    }

    /**
     * 处理支付宝的支付结果
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1、保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(infoEntity);
        //2、修改订单状态信息
        if ("TRADE_SUCCESS".equals(vo.getTrade_status()) || "TRADE_FINISHED".equals(vo.getTrade_status())) {
            //支付成功
            String outTradeNo = vo.getOut_trade_no();
            //修改订单状态
            this.baseMapper.updateOrderStatus(outTradeNo, OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }


    @Override
    public void createSecKillOrder(SeckillOrderTo secKillOrder) {
        //保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(secKillOrder.getOrederSn());
        orderEntity.setMemberId(secKillOrder.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        //算出应付价格
        BigDecimal multiply = secKillOrder.getSeckillPrice().multiply(new BigDecimal("" + secKillOrder.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(secKillOrder.getOrederSn());
        //秒杀就这一个商品，总价和上面一样
        orderItemEntity.setRealAmount(multiply);
        //TODO 获取当前sku的详细信息进行设置   productFeignService.getSpuInfoBySkuId();
        orderItemEntity.setSkuQuantity(secKillOrder.getNum());
        orderItemService.save(orderItemEntity);
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        //获取当前登录的用户
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        //从主线程中拿到之前请求中的请求头信息放入其他两个异步线程中，实现请求头共享
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //1、远程查询用户的所有的收货地址
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            System.out.println("member线程....." + Thread.currentThread().getId());
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberResponseVo.getId());
            confirmVo.setAddress(address);
        }, executor);

        //2、远程查询用户购物车所有选中的购物项（订单中要来结账这些商品）
        CompletableFuture<Void> getCartItemsFuture = CompletableFuture.runAsync(() -> {
            System.out.println("address线程....." + Thread.currentThread().getId());
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(items);
            //feign在远程调用之前要构造条件，调用很多的拦截器
            //RequestInterceptor interceptor : requestInterceptor
            //异步查询商品库存信息
        }, executor).thenRunAsync(() -> {
            //获取要查询库存的所有商品
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            //远程查询库存
            R hasStock = wmsFeignService.getSkuHasStock(collect);
            List<SkuStockVo> data = hasStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (data != null) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        }, executor);

        //3、查询用户积分
        CompletableFuture<Void> getIntegrationFuture = CompletableFuture.runAsync(() -> {
            System.out.println("integration线程....." + Thread.currentThread().getId());
            RequestContextHolder.setRequestAttributes(requestAttributes);
            Integer integration = memberResponseVo.getIntegration();
            confirmVo.setIntegration(integration);
        }, executor);

        //4、其他数据自动计算

        //5、防重复的订单令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        //服务端存放防重令牌
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId(), token, 30, TimeUnit.MINUTES);
        //页面存放防重令牌
        confirmVo.setOrderToken(token);
        CompletableFuture.allOf(getAddressFuture, getCartItemsFuture, getIntegrationFuture).get();
        return confirmVo;
    }

    /**
     * 保存订单数据
     *
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        //设置订单修改时间
        orderEntity.setModifyTime(new Date());
        //保存订单
        this.save(orderEntity);
        //订单项集合
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    //创建订单并返回完成后的订单实体对象
    private OrderCreateTo createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();
        //1、生成订单号
        String orderSn = IdWorker.getTimeId();
        //创建订单号
        OrderEntity orderEntity = buildOrder(orderSn);
        //2、获取到所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);
        //3、计算价格、积分相关
        computePrice(orderEntity, itemEntities);
        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);
        return createTo;
    }

    /**
     * 计算价格
     *
     * @param orderEntity  订单
     * @param itemEntities 订单中购物项
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");

        //对订单的各项优惠信息进行叠加（每个商品都可能会有点优惠，包括积分、优惠券……）
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");

        //订单的总额，叠加每一个订单项的总额信息
        for (OrderItemEntity entity : itemEntities) {
            coupon = coupon.add(entity.getCouponAmount());
            intergration = intergration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));
            total = total.add(entity.getRealAmount());
        }
        //1、订单价格相关
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        //设置各项优惠信息
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);
        orderEntity.setCouponAmount(coupon);
        //设置积分信息
        orderEntity.setIntegration(gift.intValue());
        //订单删除状态,0代表未删除
        orderEntity.setDeleteStatus(0);
    }

    //构建订单
    private OrderEntity buildOrder(String orderSn) {
        MemberResponseVo respVo = LoginUserInterceptor.loginUser.get();
        OrderEntity entity = new OrderEntity();
        //设置订单号
        entity.setOrderSn(orderSn);
        //设置会员id
        entity.setMemberId(respVo.getId());
        OrderSubmitVo submitVo = submitVoThreadLocal.get();
        //远程查询获取收货地址信息
        R fare = wmsFeignService.getFare(submitVo.getAddrId());
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
        });
        //设置运费信息
        entity.setFreightAmount(fareResp.getFare());
        //设置收货人信息
        entity.setReceiverCity(fareResp.getAddress().getCity());
        entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        entity.setReceiverName(fareResp.getAddress().getName());
        entity.setReceiverPhone(fareResp.getAddress().getPhone());
        entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        entity.setReceiverProvince(fareResp.getAddress().getProvince());
        entity.setReceiverRegion(fareResp.getAddress().getRegion());
        //设置订单相关状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);
        return entity;
    }

    //构建所有订单项数据
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后确定该每个购物项的价格
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            return currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                //设置订单号
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
        }
        return null;
    }

    //构建某一个订单项
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1、订单信息：订单号【buildOrderItems已经设置】
        //2、商品的spu信息【完成】
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setCategoryId(data.getCatalogId());

        //3、商品的sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        //将集合类型的skuAttr转化成String类型
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //4、优惠信息【不做】
        //5、积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //6、订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额,总额减去各种优惠
        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = orign.subtract(itemEntity.getCouponAmount()).subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);
        return itemEntity;
    }
}